package com.gitee.ixtf.sap

import com.gitee.ixtf.sap.Constant.IXTF_API_JWT_KEY
import com.gitee.ixtf.sap.application.SapDestinationDataProvider
import com.gitee.ixtf.sap.resource.RestfulResource
import com.gitee.ixtf.vertx.guice.RestfulGuice
import com.gitee.ixtf.vertx.guice.VertxGuice
import com.google.inject.Provides
import com.google.inject.Singleton
import com.sap.conn.jco.ext.DestinationDataProvider
import io.vertx.core.Future
import io.vertx.core.Vertx
import io.vertx.ext.auth.jwt.JWTAuth
import io.vertx.ext.web.handler.AuthenticationHandler
import io.vertx.ext.web.handler.JWTAuthHandler
import io.vertx.kotlin.ext.auth.jwt.jwtAuthOptionsOf
import io.vertx.kotlin.ext.auth.pubSecKeyOptionsOf

class ServiceModule(vertx: Vertx) : VertxGuice(vertx) {
  override fun configure() {
    super.configure()
    bind(DestinationDataProvider::class.java).toInstance(SapDestinationDataProvider())
    install(RestfulGuice(RestfulResource::class.java))
  }

  @Singleton
  @Provides
  private fun JWTAuth(vertx: Vertx): JWTAuth =
      JWTAuth.create(
          vertx,
          jwtAuthOptionsOf().apply {
            addPubSecKey(pubSecKeyOptionsOf(algorithm = "HS256").setBuffer(IXTF_API_JWT_KEY))
          })

  @Singleton
  @Provides
  private fun AuthenticationHandler(jwtAuth: JWTAuth): Future<AuthenticationHandler> =
      Future.succeededFuture(JWTAuthHandler.create(jwtAuth))
}
